import Vue from "vue";
import VueRouter from "vue-router";
// import Home from '../views/Home.vue'
import Login from "../views/login";
import LayOut from "@/views/layout";
import Home from "@/views/home";
import store from "@/store/index.js";
Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "/",
    name: "Home",
    component: LayOut,
    children: [
      {
        path: "",
        name: "Index",
        component: Home,
        meta: {
          isNeedLive: true
        }
      },
      {
        path: "/question",
        name: "Question",
        component: () => import("@/views/question")
      },
      {
        path: "/video",
        name: "Video",
        component: () => import("@/views/video")
      },
      {
        path: "/user",
        name: "User",
        component: () => import("@/views/user")
      }
    ]
  },
  {
    path: "/search",
    name: "Search",
    component: () => import("@/views/search")
  },
  {
    path: "/search/result",
    name: "SearchResult",
    component: () => import("@/views/search/result.vue")
  },
  {
    path: "/articleIndex/:articleId",
    name: "ArticleIndex",
    component: () => import("@/views/article")
  },
  {
    path: "/user/profile",
    name: "Profile",
    component: () => import("@/views/user/profile.vue")
  },
  {
    path: "/user/chat",
    name: "UserChat",
    component: () => import("@/views/user/chat.vue")
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
];

const router = new VueRouter({
  routes
});
console.log(router, "路由");
router.beforeEach((to, from, next) => {
  // 1 从文章列表 进入到 文章详情  isNeedLive = true
  // 2. 从文章详情回到 文章列表也是 isNeedLive = true
  // 从个人中心回到首页 要初始化 isNeedLive = false
  //从文章列表 进入 不到到 文章详情
  if (from.fullPath === "/" && !to.fullPath.startsWith("/articleIndex")) {
    from.meta.isNeedLive = false;
  }
  if (from.fullPath === "/" && to.fullPath.startsWith("/articleIndex")) {
    from.meta.isNeedLive = true;
  }
  // 从文章详情页回来的时候 进不去上面的 if
  console.log(to, "to参数");
  console.log(from, "from参数");
  console.log(next, "next");
  // 要去的一些页面需要权限  判断哪些页面 '/user'
  if (to.path.startsWith("/user")) {
    // 当前的登录状态
    if (store.state.tokenInfo.token) {
      // 如果登录了没事 next()
      next();
    } else {
      // 如果没有登录 就去登录
      next({
        path: "/login",
        query: {
          backto: to.fullPath
        }
      });
    }
  } else {
    next();
  }
});
export default router;
